//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package SaveServlet.course;

import com.lyq.bean.Course;
import com.lyq.bean.service.C_Service;
import com.lyq.bean.service.E_Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/ElectCourse_Servlet"})
public class ElectCourse_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ElectCourse_Servlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String campus = request.getParameter("campus");
        String category = request.getParameter("category");
        
        if (id == null) {
            id = "";
        }
        
        if (campus == null) {
            campus = "";
        }
        
        if (category == null) {
            category = "";
        }
        
        if (id.equals("seekall")) {
            List<Course> list = new ArrayList<>();
            // 获取所有课程，然后根据校区筛选
            list = (new C_Service()).seekAll_C(list);
            
            // 根据校区和课程类别筛选课程
            if ((campus != null && !campus.isEmpty()) || (category != null && !category.isEmpty())) {
                list = this.filterCourses(list, campus, category);
            }
            
            request.setAttribute("list", list);
            request.getRequestDispatcher("/jsp/course/s/ElectCourse.jsp?campus=" + campus + "&category=" + category).forward(request, response);
        } else if (id.equals("elect")) {
            String cNo = request.getParameter("No");
            String sNo = (String)request.getSession().getAttribute("UNAME");
            String message = "";
            
            // 检查时间冲突
            if (hasTimeConflict(cNo, sNo)) {
                message = "选课失败，与已选课程时间冲突！";
            } else {
                message = (new E_Service()).elect_C(cNo, sNo, message);
                if (message != null && !message.equals("")) {
                    // message已经包含错误信息
                } else {
                    message = "选课成功！";
                }
            }
            
            // 检查请求是否来自推荐选课页面的AJAX请求
            String xhr = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(xhr)) {
                // AJAX请求，直接返回消息文本
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write(message);
            } else {
                // 普通请求，转发到原页面
                // 直接在当前页面显示消息，而不是跳转到Message.jsp
                request.setAttribute("message", message);
                
                // 重新加载课程列表
                List<Course> list = new ArrayList<>();
                list = (new C_Service()).seekAll_C(list);
                
                // 根据校区和课程类别筛选课程
                if ((campus != null && !campus.isEmpty()) || (category != null && !category.isEmpty())) {
                    list = this.filterCourses(list, campus, category);
                }
                
                request.setAttribute("list", list);
                request.getRequestDispatcher("/jsp/course/s/ElectCourse.jsp?campus=" + campus + "&category=" + category).forward(request, response);
            }
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String select = request.getParameter("select");
        String seek = request.getParameter("seek");
        String name = request.getParameter("name");
        String campus = request.getParameter("campus");
        String category = request.getParameter("category");
        String primarySort = request.getParameter("primarySort");
        String secondarySort = request.getParameter("secondarySort");
        String thirdSort = request.getParameter("thirdSort");
        
        if (select == null) {
            select = "";
        }
        
        if (seek == null) {
            seek = "模糊查询"; // 默认使用模糊查询
        }
        
        if (name == null) {
            name = "";
        }
        
        if (campus == null) {
            campus = "";
        }
        
        if (category == null) {
            category = "";
        }
        
        if (primarySort == null) {
            primarySort = "none";
        }
        
        if (secondarySort == null) {
            secondarySort = "none";
        }
        
        if (thirdSort == null) {
            thirdSort = "none";
        }
        
        if (!name.isEmpty()) {
            List<Course> list = new ArrayList<>();
            // 根据搜索条件获取课程列表
            if (select.equals("编号") || select.equals("名称") || select.equals("授课教师")) {
                list = (new C_Service()).seek_C(select, seek, name, list);
            } else {
                // 如果不是按编号、名称或授课教师搜索，则先获取所有课程再筛选
                list = (new C_Service()).seekAll_C(list);
                list = filterCoursesByName(list, select, name);
            }
            
            // 根据校区和课程类别筛选课程
            if (!campus.isEmpty() || !category.isEmpty()) {
                list = this.filterCourses(list, campus, category);
            }
            
            // 应用排序
            list = applySorting(list, primarySort, secondarySort, thirdSort);
            
            request.setAttribute("list", list);
            if (list.size() >= 1 && list != null) {
                request.getRequestDispatcher("/jsp/course/s/ElectCourse.jsp?campus=" + campus + "&category=" + category).forward(request, response);
            } else {
                // 直接在当前页面显示消息，而不是跳转到Message.jsp
                request.setAttribute("message", "未找到你要查询的内容！");
                
                // 重新加载所有课程
                list = (new C_Service()).seekAll_C(list);
                
                // 根据校区和课程类别筛选课程
                if (!campus.isEmpty() || !category.isEmpty()) {
                    list = this.filterCourses(list, campus, category);
                }
                
                // 应用排序
                list = applySorting(list, primarySort, secondarySort, thirdSort);
                
                request.setAttribute("list", list);
                request.getRequestDispatcher("/jsp/course/s/ElectCourse.jsp?campus=" + campus + "&category=" + category).forward(request, response);
            }
        } else {
            // 如果没有输入搜索关键词，显示所有该校区的课程
            List<Course> list = new ArrayList<>();
            list = (new C_Service()).seekAll_C(list);
            
            // 根据校区和课程类别筛选课程
            if (!campus.isEmpty() || !category.isEmpty()) {
                list = this.filterCourses(list, campus, category);
            }
            
            // 应用排序
            list = applySorting(list, primarySort, secondarySort, thirdSort);
            
            request.setAttribute("list", list);
            request.getRequestDispatcher("/jsp/course/s/ElectCourse.jsp?campus=" + campus + "&category=" + category).forward(request, response);
        }
    }
    
    // 应用排序规则
    private List<Course> applySorting(List<Course> courses, String primarySort, String secondarySort, String thirdSort) {
        // 创建课程列表副本以避免修改原始列表
        List<Course> sortedCourses = new ArrayList<>(courses);
        
        // 简单排序实现 - 可以根据需要扩展更复杂的排序逻辑
        if (!"none".equals(primarySort)) {
            sortCourses(sortedCourses, primarySort);
        }
        
        return sortedCourses;
    }
    
    // 根据排序规则对课程进行排序
    private void sortCourses(List<Course> courses, String sortRule) {
        switch (sortRule) {
            case "onlineFirst":
                // 线上优先排序
                courses.sort((c1, c2) -> {
                    if ("线上".equals(c1.getCourseType()) && !"线上".equals(c2.getCourseType())) {
                        return -1;
                    } else if (!"线上".equals(c1.getCourseType()) && "线上".equals(c2.getCourseType())) {
                        return 1;
                    }
                    return 0;
                });
                break;
            case "offlineFirst":
                // 线下优先排序
                courses.sort((c1, c2) -> {
                    if ("线下".equals(c1.getCourseType()) && !"线下".equals(c2.getCourseType())) {
                        return -1;
                    } else if (!"线下".equals(c1.getCourseType()) && "线下".equals(c2.getCourseType())) {
                        return 1;
                    }
                    return 0;
                });
                break;
            case "credit":
                // 学分降序排序
                courses.sort((c1, c2) -> {
                    try {
                        double credit1 = Double.parseDouble(c1.getCredit());
                        double credit2 = Double.parseDouble(c2.getCredit());
                        return Double.compare(credit2, credit1); // 降序
                    } catch (NumberFormatException e) {
                        return 0;
                    }
                });
                break;
        }
    }
    
    // 根据搜索条件筛选课程
    private List<Course> filterCoursesByName(List<Course> courses, String select, String name) {
        List<Course> filteredCourses = new ArrayList<>();
        for (Course course : courses) {
            boolean matches = false;
            if (select.equals("编号")) {
                matches = course.getNo() != null && course.getNo().contains(name);
            } else if (select.equals("名称")) {
                matches = course.getName() != null && course.getName().contains(name);
            } else if (select.equals("授课教师")) {
                matches = course.getTeacher() != null && course.getTeacher().contains(name);
            } else if (select.equals("分类")) {
                matches = course.getCategory() != null && course.getCategory().contains(name);
            }
            
            if (matches) {
                filteredCourses.add(course);
            }
        }
        return filteredCourses;
    }
    
    // 根据校区和课程类别筛选课程
    private List<Course> filterCourses(List<Course> courses, String campus, String category) {
        List<Course> filteredCourses = new ArrayList<>();
        for (Course course : courses) {
            boolean matchesCampus = campus.isEmpty() || (course.getCampus() != null && course.getCampus().equals(campus));
            boolean matchesCategory = category.isEmpty() || (course.getCategory() != null && course.getCategory().equals(category));
            
            if (matchesCampus && matchesCategory) {
                filteredCourses.add(course);
            }
        }
        return filteredCourses;
    }
    
    // 根据校区筛选课程
    private List<Course> filterByCampus(List<Course> courses, String campus) {
        List<Course> filteredCourses = new ArrayList<Course>();
        for (Course course : courses) {
            // 修复问题：确保课程的校区信息不为空再进行比较
            if (course.getCampus() != null && course.getCampus().equals(campus)) {
                filteredCourses.add(course);
            }
        }
        return filteredCourses;
    }

    // 检查时间冲突
    private boolean hasTimeConflict(String newCourseNo, String studentNo) {
        // 获取学生已选课程
        List<Course> electedCourses = (new E_Service()).seek_ElectC(studentNo);
        
        // 获取所有课程信息
        List<Course> allCourses = new ArrayList<>();
        allCourses = (new C_Service()).seekAll_C(allCourses);
        
        // 找到新选课程的时间
        String newCourseTime = "";
        for (Course course : allCourses) {
            if (course.getNo().equals(newCourseNo)) {
                newCourseTime = course.getTime();
                break;
            }
        }
        
        // 检查与已选课程的时间是否冲突
        for (Course electedCourse : electedCourses) {
            String electedCourseNo = electedCourse.getNo();
            // 跳过自身
            if (electedCourseNo.equals(newCourseNo)) {
                continue;
            }
            
            // 获取已选课程的时间
            for (Course course : allCourses) {
                if (course.getNo().equals(electedCourseNo)) {
                    String electedCourseTime = course.getTime();
                    // 简单的时间冲突检测（实际应用中需要更复杂的逻辑）
                    if (newCourseTime.equals(electedCourseTime)) {
                        return true; // 发现时间冲突
                    }
                    break;
                }
            }
        }
        
        return false; // 没有时间冲突
    }
}